package fileStore

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"time"
)

//文件上传客户端
type StoreClient struct {
	ipport  string        //ip和端口
	group   string        //组名称（可以按照这个分集群）
	scene   string        //场景(可以按这个分类)
	timeout time.Duration //超时时间
}

//实例化文件上传客户端
//ipport ip和端口
//group  组名称（可以按照这个分集群）
//scene  场景(可以按这个分类)
//timeout 请求超时时间
func NewStoreClient(ipport string,group string,scene string,timeout time.Duration) IStoreClient {
	return &StoreClient{
		ipport:  ipport,
		group:   group,
		scene:   scene,
		timeout: timeout,
	}
}

//http客户端
var httpClient = &http.Client{}

//文件上传
func (c *StoreClient) Upload(fileName string,file []byte) (string,error) {
	body := &bytes.Buffer{}
	// 文件写入 body
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("file", fileName)
	if err != nil {
		return "", err
	}
	reader := bytes.NewReader(file)
	_, err = io.Copy(part, reader)
	// 其他参数列表写入 body
	writer.WriteField("scene", c.scene)
	writer.WriteField("output", "json2")
	if err := writer.Close(); err != nil {
		return "", err
	}
	//请求组织
	url := "http://" + c.ipport + "/" + c.group + "/upload"
	httpRequest, err := http.NewRequest("POST", url, body)
	if err != nil {
		return "", err
	}
	// 添加请求头
	httpRequest.Header.Add("Content-Type", writer.FormDataContentType())
	httpClient.Timeout = c.timeout
	// 发送请求
	resp, err := httpClient.Do(httpRequest)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	response, _ := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(response))
	result := &ResultData{}
	err = json.Unmarshal(response, result)
	if err != nil {
		return "", err
	}
	if result.Status != "ok" {
		return "", errors.New(string(response))
	}
	return result.Data.Path, nil
}

//文件删除
func (c *StoreClient) Delete(path string) (bool,error) {
	url := "http://" + c.ipport + "/" + c.group + "/delete?path=" + path
	//请求组织
	httpRequest, err := http.NewRequest("Get", url, nil)
	if err != nil {
		return false, nil
	}
	// 发送请求
	resp, err := httpClient.Do(httpRequest)
	if err != nil {
		return false, nil
	}
	defer resp.Body.Close()
	response, _ := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(response))
	result := &ResultData{}
	err = json.Unmarshal(response, result)
	if err != nil {
		return false, err
	}
	if result.Status != "ok" {
		return false, nil
	}
	return true, nil
}
